package com.ycsj.goldmedalnewconcept.activity;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.magicwindow.Session;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mob.MobSDK;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.RedPackageResponse;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.utils.TimeUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import static java.lang.Float.parseFloat;

/**
 * 创建日期：2017/11/6 13:40 描述:发送红包界面 作者:张伟
 */

@SuppressLint("NewApi")
public class SendRedPackageActivity extends Activity implements
		View.OnClickListener {

	// 取消
	private TextView tvCancel;

	// 皮肤
	private TextView tvSkin;

	// 红包金额
	private EditText etMoney;

	// 红包个数
	private EditText etHbgs;

	// 时效限制
	private TextView tvSxxz;
	
	// 红包主题
	private EditText etHbzt;

	// 塞进红包的按钮
	private Button btCommit;
	// 总金额
	private String money;
	// 红包个数
	private String redCount;
	// 时效限制
	private String time;
	// 红包主题
	private String hbzt = "学有所成,前程似锦!";
	// 上传的文件地址
	private String filePath;

	// 时间选择控件
	TimePickerView pvTime;

	private HttpUtils httpUtils1;

	private String url;

	private RequestParams params;

	private RequestParams params1;

	private String pngName;

	private String themeId = "1";

	private String imagePath;

	private Intent intent;

	protected static final int THEME_ID = 0;
	
	private String redid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_send_red_package);
		// 设置6.0以后沉浸状体栏的问题
		setBar();

		intent = getIntent();
		imagePath = intent.getStringExtra("imagePath");
		themeId = intent.getStringExtra("themeId");
		Log.e("test", "imagePath" + imagePath);
		Log.e("test", "themeId" + themeId);

		// 初始化控件
		initView();
	}

	@Override
	protected void onPause() {
		Session.onPause(this);
		super.onPause();
	}

	@Override
	protected void onResume() {
		Session.onResume(this);
		super.onResume();
	}
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		
		
//		imagePath = SPUtil.getString(this, "imagePath", "");
//		themeId =  SPUtil.getString(this, "themeId", "");
		
		
		Log.e("test", "imagePath" + imagePath);
		Log.e("test", "themeId" + themeId);
		
		super.onRestart();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		
//		SPUtil.putString(this, "imagePath", "");
//    	SPUtil.putString(this, "themeId", "");
		super.onDestroy();
	}
	/**
	 * 初始化控件
	 */
	private void initView() {
		tvCancel = (TextView) findViewById(R.id.tv_cancel);
//		tvSkin = (TextView) findViewById(R.id.tv_skin);
		tvSxxz = (TextView) findViewById(R.id.tv_sxxz);
		etMoney = (EditText) findViewById(R.id.et_money);
		etHbgs = (EditText) findViewById(R.id.et_hbgs);
		etHbzt = (EditText) findViewById(R.id.et_hbzt);
		btCommit = (Button) findViewById(R.id.bt_sjhb);
		tvCancel.setOnClickListener(this);
		tvSkin.setOnClickListener(this);
		tvSxxz.setOnClickListener(this);
		btCommit.setOnClickListener(this);
	}

	/**
	 * 点击事件
	 *
	 * @param view
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tv_cancel:
			// 取消
			finish();
			break;
//		case R.id.tv_skin:
//			// 皮肤
//			Intent intent = new Intent(this, RedPacageTemplateActivity.class);
//			startActivity(intent);
//			break;
		case R.id.tv_sxxz:
			// 时效限制
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
			
			pvTime = new TimePickerView(this,
					TimePickerView.Type.YEAR_MONTH_DAY);// 时间选择器
			pvTime.setRange(2017,2030);
			pvTime.setTime(new Date());
			pvTime.setCyclic(false);
			pvTime.setCancelable(true);
			pvTime.show();
			// 时间选择后回调
			pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

				@Override
				public void onTimeSelect(Date date) {

					
					if(TimeUtil.isTodayAfter(getTime(date))){
						tvSxxz.setText("红包有效截止时间");
						Toast.makeText(SendRedPackageActivity.this, "不可选今日之前的日期，请重新选择", Toast.LENGTH_SHORT).show();
					}else{
						tvSxxz.setText(getTime(date));
					}
				}

				public String getTime(Date date) {
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					return format.format(date);
				}
			});
			
			
			
			
			pvTime = new TimePickerView(this,
					TimePickerView.Type.YEAR_MONTH_DAY);// 时间选择器
//			pvTime.setRangeYMD(2017, 10, 23);
			pvTime.setTime(new Date());
			pvTime.setCyclic(false);
			pvTime.setCancelable(true);
			pvTime.show();
			// 时间选择后回调
			pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
				
				@Override
				public void onTimeSelect(Date date) {
					
					tvSxxz.setText(getTime(date));
					
				}
				
				public String getTime(Date date) {
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					return format.format(date);
				}
			});

			break;
		case R.id.bt_sjhb:
			// 塞进红包
			judgeAll();
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {

			case THEME_ID:

				break;
			}
		}
	}

	/**
	 * 点击塞进红包后按钮后的判断完整性方法
	 */
	private void judgeAll() {
		
		// 获取金额
		money = etMoney.getText().toString().trim();
		if (TextUtils.isEmpty(money)) {
			Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
			return;
		}

		// 红包个数
		redCount = etHbgs.getText().toString().trim();
		if (TextUtils.isEmpty(redCount) || Integer.parseInt(redCount) <= 0) {
			Toast.makeText(this, "请至少输入一个红包个数", Toast.LENGTH_SHORT).show();
			return;
		}

		// 时效限制时间
		time = tvSxxz.getText().toString().trim();
		Log.e("time", time);
		if (TextUtils.isEmpty(time)) {
			Toast.makeText(this, "请选择红包有效截止时间", Toast.LENGTH_SHORT).show();
			return;
		}
		
		if ("红包有效截止时间".equals(time)) {
			Toast.makeText(this, "请选择红包有效截止时间", Toast.LENGTH_SHORT).show();
			return;
		}

		// 红包主题
		hbzt = etHbzt.getText().toString().trim();

		// 判断总金额/红包个数的值是否大于1,保证每个人至少能拿到1块钱以上的红包
		float getMoney = Float.parseFloat(money) / parseFloat(redCount);
		if (getMoney < 1) {
			
			
			//请保证每个人至少能得到一块钱红包
			moneydialog();
			
//			Toast.makeText(this, "请保证每个人至少能得到一块钱红包", Toast.LENGTH_SHORT).show();
			return;
		}
		dialog();
	}
	
	
	//请保证每个人至少能得到一块钱红包
	private void moneydialog() {
		final NormalDialog dialog = new NormalDialog(
				SendRedPackageActivity.this);
		dialog.content("您输入的红包金额必须保证每人最少可领取1元")
				.btnText("取消", "确认")//
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(23)//
				.show();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

			@Override
			public void onBtnLeftClick() {
				dialog.dismiss();
			}
		});
		dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

			@Override
			public void onBtnRightClick() {
				dialog.dismiss();
			}
		});
	}

	private void dialog() {
		final NormalDialog dialog = new NormalDialog(
				SendRedPackageActivity.this);
		dialog.content("确定发红包吗？")
				.btnText("取消", "确认")//
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(23)//
				.show();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

			@Override
			public void onBtnLeftClick() {
				dialog.dismiss();
			}
		});
		dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

			@Override
			public void onBtnRightClick() {
				dialog.dismiss();
				
				if(hbzt==null||"".equals(hbzt)){
					hbzt = "学有所成,前程似锦!";
				}
				if(themeId==null||"".equals(themeId)){
					themeId = "1";
				}
				
				// 请求服务器上传用户填写的相关信息
				if (imagePath == null || "".equals(imagePath)) {
					creatRedPackage();// 无编辑自定义模板图片
				} else {
					File f = new File(getCacheDir(), imagePath);

					creatImageRedPackage();
				}
			}
		});
	}

	 private void creatImageRedPackage() {
	 // TODO Auto-generated method stub
	 HttpUtils httpUtils = new HttpUtils();
//	 url = "http://pm.moregolden.com/ycsj_platform/RedPacketMsg";
	 url = Constant.SERVER_URL+"RedPacketMsg";
	 
	 //http://pm.moregolden.com/ycsj_platform/RedPacketMsg?type=10&c=13554126512&role=3&money=20&persons
	 //=1&expiration=2017-11-11&title=学有所成，前程似锦!&schoolId=10361&schoolName=魅族1中&skinId=2&havepic=1
	
	 params = new RequestParams();
	 params.addBodyParameter("type", "10");
	 params.addBodyParameter("c",SPUtil.getString(SendRedPackageActivity.this,
	 "account", ""));
	 params.addBodyParameter("role",
	 SPUtil.getString(SendRedPackageActivity.this, "role", ""));
	 params.addBodyParameter("money", money);
	 params.addBodyParameter("persons", redCount);
	 params.addBodyParameter("expiration", time);
	 params.addBodyParameter("title", hbzt);
	 params.addBodyParameter("schoolId",
	 SPUtil.getString(SendRedPackageActivity.this, "schoolId", ""));
	 params.addBodyParameter("schoolName",
	 SPUtil.getString(SendRedPackageActivity.this, "schoolName", ""));
	 params.addBodyParameter("skinId", themeId);
	 params.addBodyParameter("havepic", "1");
	
	 
	
	 String path = getSDPath() + "/goldupload/" + imagePath + ".png";
	 
	 File f = new File(path);
	  String[] split = path.split("\\/");
	  String name = split[split.length - 1];
	  
	  
	 params.addBodyParameter("Filedata",f);
	
	
	 httpUtils.send(HttpMethod.POST, url, params, callBackHeadimg);
	
	 }
	 private RequestCallBack<String> callBackHeadimg = new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				String json = responseInfo.result;
				Log.e("imgred", json);
				Gson gson = new Gson();
				RedPackageResponse fromJson = gson.fromJson(json,
						RedPackageResponse.class);
				if (fromJson != null) {
					if ("1".equals(fromJson.state)) {
						Log.e("test", "发红包成功");
						redid = fromJson.redId;

						ShareRedpackage();
					} else {
						Toast.makeText(SendRedPackageActivity.this, "服务器开小差了", 0)
								.show();
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Toast.makeText(SendRedPackageActivity.this, "网络无响应，请检查网络连接是否正常", 0)
						.show();
			}
		};
	 
	 
	public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			sdDir = getFilesDir();
		}
		return sdDir.toString();
	}

	private void creatRedPackage() {

		HttpUtils httpUtils1 = new HttpUtils();
//		url = "http://pm.moregolden.com/ycsj_platform/RedPacketMsg";
		url = Constant.SERVER_URL + "RedPacketMsg";
		
		// http://192.168.0.164:8080/ycsj_platform/RedPacketMsg?type=1&c=15871695200_0&role=3&money=哈哈&persons
		// =&expiration=3&title=&schoolId=3&schoolName=

		params1 = new RequestParams();
		params1.addBodyParameter("type", "1");
		params1.addBodyParameter("c",
				SPUtil.getString(SendRedPackageActivity.this, "account", ""));
		params1.addBodyParameter("role",
				SPUtil.getString(SendRedPackageActivity.this, "role", ""));
		params1.addBodyParameter("money", money);
		params1.addBodyParameter("persons", redCount);
		params1.addBodyParameter("expiration", time);
		params1.addBodyParameter("title", hbzt);
		params1.addBodyParameter("schoolId",
				SPUtil.getString(SendRedPackageActivity.this, "schoolId", ""));
		params1.addBodyParameter("schoolName",
				SPUtil.getString(SendRedPackageActivity.this, "schoolName", ""));
		params1.addBodyParameter("skinId", themeId);
		params1.addBodyParameter("havepic", "0");


		httpUtils1.send(HttpMethod.POST, url, params1, callBackHeadimg1);

	}

	private RequestCallBack<String> callBackHeadimg1 = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			Log.e("test", json);
			Gson gson = new Gson();
			RedPackageResponse fromJson = gson.fromJson(json,
					RedPackageResponse.class);
			if (fromJson != null) {
				if ("1".equals(fromJson.state)) {
					Log.e("test", "发红包成功");
					redid = fromJson.redId;

					ShareRedpackage();

				} else {
					Toast.makeText(SendRedPackageActivity.this, "服务器开小差了", 0)
							.show();
				}
			}
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			Toast.makeText(SendRedPackageActivity.this, "网络无响应，请检查网络连接是否正常", 0)
					.show();
		}
	};

	private void ShareRedpackage() {
		
		if(redid==null||"".equals(redid)){
			
			Toast.makeText(SendRedPackageActivity.this, "服务器开小差了,请重试", 0)
			.show();
			return;
		}
		if(hbzt==null||"".equals(hbzt)){
			hbzt = "学有所成,前程似锦!";
		}
		

		
//		Resources r = this.getResources();
//		InputStream is = r.openRawResource(R.drawable.redbag);
//		BitmapDrawable  bmpDraw = new BitmapDrawable(is);
//		final Bitmap mBitmap = bmpDraw.getBitmap();
		
		
		// TODO Auto-generated method stub
		MobSDK.init(SendRedPackageActivity.this, "12c24ea0b59b0",
				"aae63565fbd69b1acbfcdd0d5ac0b35c");
		OnekeyShare oks = new OnekeyShare();
		// 关闭sso授权
		oks.disableSSOWhenAuthorize();
		oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

			@Override
			public void onShare(Platform platform, ShareParams paramsToShare) {
				
				
				
				
//				if(QQ.NAME.equals(platform.getName())){
//					
//					
//					
//				}else
				if (SinaWeibo.NAME.equals(platform.getName())) {
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					// http://m.moregolden.com:36356/redBag/redBag.html?rid=
					String url = Constant.SERVER_tk+":36356/redBag/redBag.html?rid="+redid;
//					String url = "http://139.129.213.183:36356/redBag/redBag.html?rid="+redid;
//					String url = "http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid;
							
					String title = "来自"+SPUtil.getString(SendRedPackageActivity.this, "schoolName", "")+"学校的红包";
					int unicodeJoy = 0x1F44D;
					String emojiString = new String(Character
							.toChars(unicodeJoy));
					paramsToShare.setTitleUrl(Constant.SERVER_tk+":36356/redBag/redBag.html?rid="+redid);
//					paramsToShare.setTitleUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					paramsToShare.setTitle("来自"+SPUtil.getString(SendRedPackageActivity.this, "schoolName", "")+"学校的红包");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText(hbzt);
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					
					
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/redbag.png");
//					paramsToShare.setImageData(mBitmap);

					
					
					
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl(Constant.SERVER_tk+":36356/redBag/redBag.html?rid="+redid);
//					paramsToShare.setUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
//					paramsToShare.setSite(getString(R.string.app_name));
					paramsToShare.setSite("金牌君");
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl(Constant.SERVER_tk+":36356/redBag/redBag.html?rid="+redid);
//					paramsToShare.setSiteUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);

				} else {
					paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
					paramsToShare.setTitle(getString(R.string.share));
					// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
					paramsToShare.setTitleUrl(Constant.SERVER_tk+":36356/redBag/redBag.html?rid="+redid);
//					paramsToShare.setTitleUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					paramsToShare.setTitle("来自"+SPUtil.getString(SendRedPackageActivity.this, "schoolName", "")+"学校的红包");
					// text是分享文本，所有平台都需要这个字段
					paramsToShare.setText(hbzt);
					// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
					// oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
					paramsToShare
							.setImageUrl("http://139.129.57.83:8080/Appandroid/redbag.png");
					
					
//					paramsToShare.setImageData(mBitmap);
					// url仅在微信（包括好友和朋友圈）中使用
					paramsToShare.setUrl(Constant.SERVER_tk+":36356/redBag/redBag.html?rid="+redid);
//					paramsToShare.setUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);
					// comment是我对这条分享的评论，仅在人人网和QQ空间使用
					paramsToShare.setComment("");
					// site是分享此内容的网站名称，仅在QQ空间使用
					paramsToShare.setSite("金牌君");
//					paramsToShare.setSite(getString(R.string.app_name));
					// siteUrl是分享此内容的网站地址，仅在QQ空间使用
					paramsToShare.setSiteUrl(Constant.SERVER_tk+":36356/redBag/redBag.html?rid="+redid);
//					paramsToShare.setSiteUrl("http://m.moregolden.com:36356/redBag/redBag.html?rid="+redid);

				}
			}
		});
		// 分享时Notification的图标和文字 2.5.9以后的版本不 调用此方法
		// oks.setNotification(R.drawable.ic_launcher,
		// getString(R.string.app_name));
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用

		// 启动分享GUI
		oks.show(this);
	}

	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}
}
